//
//  LogginViewController.swift
//  我的微博
//
//  Created by 吴加将 on 15/9/8.
//  Copyright © 2015年 吴加将. All rights reserved.
//

import UIKit
import SVProgressHUD

class LogginViewController: UIViewController,UIWebViewDelegate {
   private lazy var webview = UIWebView()
    override func loadView() {
        view=webview
        webview.delegate=self
        title="新浪微博"
        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain
            , target: self, action: "close")
        
    }
    func close(){
        SVProgressHUD.dismiss()

        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //view.backgroundColor=UIColor.whiteColor()
        
        webview.loadRequest(NSURLRequest(URL: SessionTool.sharedNetworktool.oauthUrl()))
    }
    func webViewDidStartLoad(webView: UIWebView) {
      //  SVProgressHUD.show()
        print("开始")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
       // SVProgressHUD.dismiss()
        print("结束")
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request)
        let urlSTring = request.URL!.absoluteString
        //判断是否包含回调地址
        if !urlSTring.hasPrefix(SessionTool.sharedNetworktool.redirectUri){
            return true
        }
        //判断参数
        if let query = request.URL!.query where query.hasPrefix("code") {
            let code=query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            //
            loadAccessToken(code)
            
        }else{
            close()
        }
        print(urlSTring)
        
        
        return false
        
    }
    func loadAccessToken(code:String){
        SessionTool.sharedNetworktool.loadToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
     let time = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
                
         dispatch_after(time, dispatch_get_main_queue()) {
            self.close()
         }
                return
            }
            print(result)
             let tokens = userTokens(dict: result!)
        }
    }

}
